import React, { useState, useEffect, useRef } from "react";
import { Tabs, Empty } from "antd-mobile";
import * as echarts from "echarts";
import { locationShape, historyShape, storeShape } from "src/propType";
import PropTypes from "prop-types";

const dWidth = document.body.clientWidth;
const isMobile = dWidth < 500;
const height = isMobile ? 400 : 320;
const color = [
    "#22D7BB",
    "#24AAFF",
    "#5EDDF8",
    "#F89C3E",
    "#4CC1FF",
    "#BA5537",
    "#6A7AFC",
    "#6EC45A",
    "#F8CF32",
];

const colors = (function getColor() {
    let colorMap = {};
    color.forEach((_, i) => {
        colorMap[`r${i}`] = {
            align: "right",
            color: _,
            width: 40,
        };
    });
    return colorMap;
})();

const FileCountChart = props => {
    const [currentMenu, setMenu] = useState(1000008142);
    const fileCartRef = useRef(null);

    const { store, history, homeCardData, scroll } = props;

    useEffect(() => {
        if (fileCartRef.current) {
            initEcharts(currentMenu);
        }
    }, [fileCartRef, homeCardData, scroll]);

    const initEcharts = tableId => {
        const _chart = echarts.init(fileCartRef.current, null, {
            width: dWidth - 44,
            height,
        });
        const targetData = homeCardData.find(item => item.tableId == tableId);
        if (!targetData) return;
        const chartData = targetData.data.map(item => ({
            value: item.scount,
            name: item.moduleName,
        }));
        let options = {
            title: {
                text: targetData.title,
                left: "center",
                top: 20,
                textStyle: {
                    fontSize: 14,
                },
            },
            color,
            tooltip: {
                trigger: "item",
                formatter: "{b} <br/> {c} ({d}%)",
            },
            grid: {
                top: 0,
                right: 0,
                left: 0,
            },
            legend: {
                orient: "horizontal",
                top: 200,
                align: "left",
                itemWidth: 10, // 图例标记的宽度
                itemHeight: 10, // 图例标记的高度
                itemGap: 10, // 图例之间的间距
                icon: "circle",
                data: chartData,
                textStyle: {
                    fontSize: 12, // 文本字体大小
                    rich: {
                        l: {
                            width: 140, // 名称部分的宽度

                            align: "left", // 名称左对齐
                        },
                        ...colors,
                    },
                },
                formatter: function (name) {
                    const total = chartData.reduce((sum, item) => sum + item.value, 0); // 计算总和
                    const idx = chartData.findIndex(item => item.name === name);
                    const value = chartData[idx]?.value || 0;
                    const percent = total === 0 ? 0 : ((value / total) * 100).toFixed(2); // 计算百分比并保留两位小数
                    const styleIdx = `r${idx}`;
                    return `{l|${name}} {${styleIdx}|(${value})} {${styleIdx}|${percent}%}`; // 返回格式化后的字符串
                },
            },
            series: [
                {
                    name: "文件数量统计",
                    type: "pie",
                    radius: "40%",
                    center: ["50%", isMobile ? "30%" : "40%"],
                    data: chartData,
                    label: {
                        show: false,
                    },
                    emphasis: {
                        itemStyle: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: "rgba(0, 0, 0, 0.5)",
                        },
                    },
                },
            ],
        };
        _chart.setOption(options);
    };

    const hasData = homeCardData?.length;

    const handleOption = activeKey => {
        setMenu(activeKey);
        initEcharts(activeKey);
    };

    return (
        <div className="fileCount-container">
            <Tabs activeKey={currentMenu} onChange={handleOption}>
                {homeCardData.map(tab => {
                    return <Tabs.Tab title={tab.title} key={tab.tableId} />;
                })}
            </Tabs>
            {hasData ? (
                <div className="chart-container" style={{ height: `${height}px` }}>
                    <div className="fileChart" ref={fileCartRef}></div>
                </div>
            ) : (
                <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
            )}
        </div>
    );
};

FileCountChart.propTypes = {
    history: historyShape,
    location: locationShape,
    store: storeShape,
    homeCardData: PropTypes.array,
    scroll: PropTypes.object,
};

export default FileCountChart;
